package service

import (
	"context"
	"errors"
	"github.com/gin-gonic/gin"
	"github.com/robin/webook/internal/domain"
	"github.com/robin/webook/internal/repository"
	"golang.org/x/crypto/bcrypt"
)

var (
	ErrInvalidUserOrPassword = errors.New("用户名不存在或者密码不对")
)

type UserService struct {
	repo *repository.UserRepository
}

func NewUserService(repo *repository.UserRepository) *UserService {
	return &UserService{
		repo: repo,
	}
}

func (svc *UserService) Signup(ctx context.Context, user domain.User) error {
	hashedPassword, err := bcrypt.GenerateFromPassword([]byte(user.Password), bcrypt.DefaultCost)
	if err != nil {
		return err
	}

	user.Password = string(hashedPassword)
	return svc.repo.Create(ctx, user)
}

func (svc *UserService) Login(ctx *gin.Context, email, password string) (domain.User, error) {
	u, err := svc.repo.FindByEmail(ctx, email)
	if errors.Is(err, repository.ErrUserNotFound) {
		return u, ErrInvalidUserOrPassword
	}

	if err != nil {
		return domain.User{}, err
	}

	// 校验密码
	err = bcrypt.CompareHashAndPassword([]byte(u.Password), []byte(password))
	if err != nil {
		return domain.User{}, ErrInvalidUserOrPassword
	}

	// 所有校验通过
	return u, nil
}
